package com.yfl.logistics.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.yfl.logistics.pojo.User;
import com.yfl.logistics.pojo.UserExample;
import com.yfl.logistics.pojo.msgObject;
import com.yfl.logistics.service.UserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

@Controller
@RequestMapping("/admin")
public class AdminController {

    @Autowired
    private UserService userService;

    @RequestMapping("/adminPage")
    public String adminPage() {
        return "adminPage";
    }

    @RequestMapping("/list")
    @ResponseBody
    public PageInfo<User> list(@RequestParam(defaultValue = "1") Integer pageNum,
                               @RequestParam(defaultValue = "10") Integer pageSize,
                               String keyword) {


        //开始分页
        PageHelper.startPage(pageNum, pageSize);
        UserExample example = new UserExample();

        if (StringUtils.isNotBlank(keyword)) {
            //创建限制对象
            UserExample.Criteria criteria1 = example.createCriteria();
            criteria1.andUsernameLike("%" + keyword + "%");

            UserExample.Criteria criteria2 = example.createCriteria();
            criteria2.andRealnameLike("%" + keyword + "%");

            example.or(criteria2);

            UserExample.Criteria criteria3 = example.createCriteria();
            criteria3.andRolenameLike("%" + keyword + "%");

            example.or(criteria3);

        }


        List<User> users = userService.selectByExample(example);

        //返回分页对象

        return new PageInfo<User>(users);
    }

    //删除操作
    @RequestMapping("/delete")
    @ResponseBody
    public msgObject  deleteUser(Long userId){

        int row = userService.deleteByPrimaryKey(userId);

        msgObject mo = msgObject.creatMsgObject(0, "删除失败");

        if (row == 1){

           mo= msgObject.creatMsgObject(1,"删除成功");
        }

        return  mo;
    }

}
